package xyz.yeidi.dao.impl;

import xyz.yeidi.dao.api.DeliveryAddressDao;
import xyz.yeidi.pojo.Deliveryaddress;
import xyz.yeidi.utils.ConnUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author JIP
 * @Date 2021-08-06 11:00
 * @Version 1.0
 * @Describe :
 */
public class DeliveryAddressDaoImpl implements DeliveryAddressDao {
    @Override
    public List<Deliveryaddress> getAllAddressByUserId(Integer userId) throws Exception {
        String sql = "select daId,contactName,contactSex,contactTel,address " +
                "from deliveryaddress where userId = ?";
        List<Deliveryaddress> deliveryaddress = new ArrayList<>();
        Connection conn = ConnUtils.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,userId);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            Deliveryaddress address = new Deliveryaddress();
            address.setDaId(rs.getLong(1));
            address.setContactName(rs.getString(2));
            address.setContactSex(rs.getInt(3));
            address.setContactTel(rs.getString(4));
            address.setAddress(rs.getString(5));
            address.setUserId(userId);
            deliveryaddress.add(address);
        }
        ConnUtils.close(rs,ps);
        return deliveryaddress;
    }

    @Override
    public Deliveryaddress getAddressById(Integer id) throws Exception {
        return null;
    }

    @Override
    public boolean addAddress(Deliveryaddress deliveryaddress) throws Exception {
        String sql = "insert into deliveryaddress(contactName, contactSex, contactTel, address, userId)" +
                "values (?,?,?,?,?)";
        Connection conn = ConnUtils.getConnection();
        boolean flag = true;
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,deliveryaddress.getContactName());
        ps.setObject(2,deliveryaddress.getContactSex());
        ps.setObject(3,deliveryaddress.getContactTel());
        ps.setObject(4,deliveryaddress.getAddress());
        ps.setObject(5,deliveryaddress.getUserId());
        if(ps.executeUpdate()==0){
            flag = false;
        }
        ConnUtils.close(ps);
        return flag;
    }
}
